﻿using System;
using System.Globalization;
using System.Windows.Data;

using FMOD;

namespace LaunchPad.Core.Controls.Tracks
{
    [ValueConversion(typeof(TimeSpan), typeof(double))]
    public class TimePositionConverter : IValueConverter
    {
        public AudioTrack Track { get; set; }
        public double ZoomFactor { get; set; }
        public double BaseScale { get; set; }

        public TimePositionConverter()
        {
            //BaseScale = 0.0005;
            BaseScale = 0.0001;
        }

        public TimePositionConverter(AudioTrack track) : this()
        {
            Track = track;
        }

        public TimePositionConverter(AudioTrack track, double zoomFactor) :
            this(track)
        {
            if (zoomFactor == 0)
                throw new ArgumentOutOfRangeException("zoomFactor");

            ZoomFactor = zoomFactor;
        }

        public TimeSpan GetTime(double position)
        {
            if (Track == null)
                return TimeSpan.Zero;

            return Track.ToTime(position / ZoomFactor / BaseScale);
        }

        public double GetPosition(TimeSpan time)
        {
            if (Track == null)
                return 0;
            return Track.ToSamples(time) * ZoomFactor * BaseScale;
        }

        public object Convert(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            return GetPosition((TimeSpan)value);
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            return GetTime((double)value);
        }
    }
}
